package common

import (
	"context"
	"encoding/json"
	"fanqiechaodan-blog/config"
	"fanqiechaodan-blog/dao"
	"fanqiechaodan-blog/models"
	"fanqiechaodan-blog/redis"
	"fmt"
	"io"
	"net/http"
	"sync"
	"time"
)

var Template *models.HtmlTemplate

func LoadTemplate() {
	group := sync.WaitGroup{}
	group.Add(1)
	go func() {
		var err error
		Template, err = models.InitTemplate(config.Cfg.System.CurrentDir + "/template/")
		if err != nil {
			panic(err)
		}
		group.Done()
	}()
	group.Wait()
}

func GetRequestJSONParam(request *http.Request) map[string]interface{} {
	var res map[string]interface{}
	bytes, _ := io.ReadAll(request.Body)
	_ = json.Unmarshal(bytes, &res)
	return res
}

func Success(w http.ResponseWriter, data any) {
	var res models.Result
	res.Data = data
	res.Code = http.StatusOK
	bytes, _ := json.Marshal(res)
	w.Header().Set("Content-Type", "application/json")
	w.Write(bytes)
}

func Error(w http.ResponseWriter, err error) {
	var res models.Result
	res.Code = http.StatusInternalServerError
	res.Error = err.Error()
	bytes, _ := json.Marshal(res)
	w.Header().Set("Content-Type", "application/json")
	w.Write(bytes)
}

func UpdateViewCount(pid int) {
	get := redis.RDB.Get(context.Background(), fmt.Sprintf("post_view_count:%v", pid))
	if get.Val() == "" {
		_ = dao.UpdatePostViewCount(pid)
		redis.RDB.Set(context.Background(), fmt.Sprintf("post_view_count:%v", pid), "1", time.Minute)
	}
}
